/* eslint-disable no-param-reassign */
/* eslint-disable prefer-destructuring */
/* eslint-disable eqeqeq */
import React, { PureComponent } from 'react';
import moment from 'moment';
import 'moment/locale/zh-cn';
import router from 'umi/router';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import { CloseOutlined, UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Input,
  Select,
  Row,
  Col,
  Checkbox,
  message,
  DatePicker,
  Upload,
} from 'antd';
import { connect } from 'dva';
import queryString from 'query-string';
import ReactQuill from 'react-quill'; // 引入富文本编辑器
import downloadFile, { requestHeadersMd5 } from '@/utils/utils';
import 'react-quill/dist/quill.snow.css';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; // 引入头部组件
import styles from './index.less';

const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const { Option } = Select;

@connect(({ guideprotect }) => ({
  guideprotect,
}))
class BasicList extends PureComponent {
  state = {
    oldFileList: [],
    fileList: [],
  };

  componentDidMount() {
    const { dispatch, location, form } = this.props;
    dispatch({
      type: 'guideprotect/queryDictItemsByCodes',
      payload: ['BIZ_INS_TYPE', 'BIZ_ACCU_TYPE'],
    });
    const { id } = queryString.parse(location.search);
    dispatch({
      type: 'guideprotect/updateModelData',
      payload: {
        detailId: id,
      },
    });
    dispatch({
      type: 'guideprotect/getContent',
      payload: {
        plcyId: id,
      },
    }).then(res => {
      if (res.success) {
        if (res.data.affix && res.data.affix.length) {
          this.setState({ oldFileList: this.handleAffix(res.data.affix) });
        }
        form.setFieldsValue({
          tit: res.data.tit,
          type: res.data.type.split(','),
          areaId: { key: res.data.areaId, label: res.data.areaName },
          source: res.data.source,
          keyWord: res.data.keyWord,
        });
        if (res.data.publishTime) {
          form.setFieldsValue({
            publishTime: moment(res.data.publishTime),
          });
        } else {
          form.resetFields('publishTime');
        }
      }
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'guideprotect/updateModelData',
      payload: {
        policyData: [],
        cityChild: [],
        affixArr: [],
        contentData: {},
        content: '',
        vno: '',
        detailId: '',
      },
    });
  }

  // 富文本编辑器 时间
  handleChange = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'guideprotect/updateModelData',
      payload: {
        content: value,
      },
    });
  };

  // 处理附件返回值
  handleAffix = fileList => {
    const tempArr = [];
    fileList.split(',').forEach(value => {
      const tempJson = {};
      tempJson.fileId = value.split('|')[0];
      tempJson.fileName = value.split('|')[1];
      tempArr.push(tempJson);
    });
    return tempArr;
  };

  // 取消
  goBack = () => {
    router.push('/searchmanage/guideprotect/index');
  };

  handleSubmit = e => {
    e.preventDefault();
    const {
      form,
      guideprotect: { vno, content, detailId },
      dispatch,
    } = this.props;
    const { oldFileList } = this.state;
    // return
    form.validateFields((err, values) => {
      // 处理入参格式
      if (!err) {
        const tempArr = [];
        const fileArr = [];
        let affix = '';
        if (values.affix) {
          values.affix.forEach(value => {
            if (value.response.success) {
              tempArr.push(value.response.data);
            }
          });
        }
        if (oldFileList.length) {
          oldFileList.forEach(value => {
            fileArr.push(`${value.fileId}|${value.fileName}`);
          });
        }
        affix = tempArr.concat(fileArr).join(',');
        values.type = values.type.join(',');
        values.affix = affix;
        values.content = content;
        values.publishTime = values.publishTime ? values.publishTime.valueOf() : '';
        values.plcyId = detailId;
        values.vno = vno;
        const tempAreaId = values.areaId.key;
        const tempAreaName = values.areaId.label;
        values.areaId = tempAreaId;
        values.areaName = tempAreaName;
        dispatch({
          type: 'guideprotect/update',
          payload: values,
        });
      }
    });
  };

  cityChange = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'guideprotect/cityChange',
      payload: { areaName: value },
    });
  };

  normFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  // 删除附件
  delFile = (id, oldFileList) => {
    const newData = oldFileList.filter(item => item.fileId !== id);
    this.setState({ oldFileList: newData });
  };

  downLoad = item => {
    downloadFile({ fileId: item.fileId, fileName: item.fileName });
  };

  render() {
    const {
      form: { getFieldDecorator },
      guideprotect: { cityChild, policyData, content },
    } = this.props;

    const { oldFileList, fileList } = this.state;
    const tempCityChild = cityChild.map(value => (
      <Option key={value.areaId} value={value.areaId}>
        {value.areaName}
      </Option>
    ));
    const formItemLayout = {
      labelCol: { md: { span: 4 } },
      wrapperCol: { md: { span: 16 } },
    };

    const nowModules = {
      toolbar: [
        [{ header: [1, 2, 3, 4, 5, 6, false] }], // 文字大小
        ['bold', 'italic', 'underline'], // 切换组，【加粗、倾斜、下划线、删除线strike】
        //      ['blockquote', 'code-block'],   // 左竖线     代码格式   二选一
        //      [{ 'header': 1 }, { 'header': 2 }],               // 标题大小
        [{ list: 'ordered' }, { list: 'bullet' }], // 列表，数字|黑点 标记
        //      [{ 'script': 'sub'}, { 'script': 'super' }],      // 右下标，右上标
        //      [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
        //      [{ 'direction': 'rtl' }],                         // text direction
        [{ size: ['small', false, 'large', 'huge'] }], // 行距
        [{ color: [] }, { background: [] }], // 文字颜色，背景色
        [{ font: [] }], // font-family
        [{ align: [] }], // text-align
        ['clean'], // 清除所有样式
      ],
    };
    // 富文本编辑器总配置
    const quillConfig = {
      theme: 'snow',
      modules: nowModules,
      placeholder: '请输入政策内容',
    };
    const props = {
      name: 'file',
      // action: '/osApi/sys/uploadFile',
      action: '/osApi/fileServer/uploadFile',
      headers: {
        authorization: 'authorization-text',
        ...requestHeadersMd5(),
      },
      onChange(info) {
        if (info.file.status === 'done') {
          message.success(`${info.file.name} 上传成功！`);
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 上传失败！`);
        }
      },
    };

    return (
      <div>
        <PageHeaderWrapper>
          <Card title="政策修改">
            <Form>
              <FormItem {...formItemLayout} label="政策标题">
                {getFieldDecorator('tit', {
                  rules: [{ required: true, message: '请输入政策标题' }],
                })(<Input placeholder="请输入供应商名称" style={{ width: 200 }} />)}
              </FormItem>
              <FormItem {...formItemLayout} label="政策类型">
                {getFieldDecorator('type', {
                  rules: [{ required: true, message: '请选择政策类型' }],
                })(
                  <CheckboxGroup style={{ width: '100%' }}>
                    {/* <Row> */}
                    {policyData &&
                      policyData.map(value => (
                        /* <Col span={4} key={value.itemCode}> */
                        <Checkbox value={value.itemCode}>{value.itemName}</Checkbox>
                        /* </Col> */
                      ))}
                    {/* </Row> */}
                  </CheckboxGroup>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="政策地区">
                {getFieldDecorator('areaId', {
                  rules: [{ required: true, message: '请输入政策地区' }],
                })(
                  <Select
                    labelInValue
                    filterOption={false}
                    notFoundContent={null}
                    onSearch={this.cityChange}
                    showSearch
                  >
                    {tempCityChild}
                  </Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="来源">
                {getFieldDecorator('source', {
                  rules: [{ required: false, message: '请输入来源' }],
                })(<Input placeholder="请输入来源" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="公布时间">
                {getFieldDecorator('publishTime', {
                  rules: [{ required: false, message: '请选择公布时间' }],
                })(<DatePicker locale={locale} />)}
              </FormItem>
              <FormItem {...formItemLayout} label="关键字">
                {getFieldDecorator('keyWord', {
                  rules: [{ required: true, message: '请输入关键字' }],
                })(<Input placeholder="请输入关键字(多个关键字请用逗号隔开)" />)}
              </FormItem>

              <Row style={{ marginTop: 15, minHeight: '250px', marginBottom: 20 }}>
                <Col
                  span={4}
                  offset={0}
                  className={styles.selfLabel}
                  style={{ lineHeight: '32px' }}
                >
                  <span style={{ color: 'red', marginRight: 4 }}>*</span>
                  <span style={{ color: '#7F7F7F' }}>政策内容 :</span>&nbsp;&nbsp;&nbsp;
                </Col>
                <Col span={16} offset={0}>
                  <ReactQuill
                    value={content || ''}
                    onChange={this.handleChange}
                    style={{ height: '200px', overflowY: 'visible' }}
                    {...quillConfig}
                  />
                </Col>
              </Row>

              <FormItem {...formItemLayout} label="上传附件">
                {getFieldDecorator('affix', {
                  valuePropName: 'fileList',
                  getValueFromEvent: this.normFile,
                  initialValue: fileList,
                })(
                  <Upload {...props}>
                    <Button>
                      <UploadOutlined /> 点击上传
                    </Button>
                  </Upload>
                )}
              </FormItem>
              {oldFileList && oldFileList.length ? (
                <Row>
                  {oldFileList.map(item => (
                    <Col key={item.fileId} style={{ marginBottom: 10 }} offset={4}>
                      <a onClick={() => this.downLoad(item)} style={{ textDecoration: 'none' }}>
                        {item.fileName}
                      </a>
                      <CloseOutlined
                        style={{
                          marginLeft: 30,
                          lineHeight: '20px',
                          color: '#40a9ff',
                          fontSize: '12px',
                        }}
                        onClick={() => this.delFile(item.fileId, oldFileList)} />
                    </Col>
                  ))}
                </Row>
              ) : null}
            </Form>
          </Card>
          <FooterToolbar>
            <Button onClick={this.goBack} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button type="primary" onClick={this.handleSubmit}>
              提交
            </Button>
          </FooterToolbar>
        </PageHeaderWrapper>
      </div>
    );
  }
}

const WrappedHorizontalLoginForm = Form.create()(BasicList);

export default WrappedHorizontalLoginForm;
